package com.dimong.www.loan.db;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by wuligang on 2018/5/29.
 */

public class CheckTotalDao {
    private Context context;
    private Dao<CheckTotalModel, Integer> dao;

    public CheckTotalDao(Context context) {
        this.context = context;
        try {
            this.dao = OpenHelperManager.getHelper(context,
                LoanDBHelper.class).getDao(CheckTotalModel.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void insert(CheckTotalModel data) {
        try {
            dao.createOrUpdate(data);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 查询user表中的所有数据
    public List<CheckTotalModel> selectAll() {
        List<CheckTotalModel> users = null;
        try {
            users = dao.queryForAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return users;
    }

    public void deletaAll() {
        try {
            dao.executeRawNoArgs("delete from check");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public CheckTotalModel findOneRecord(int year, int month, int day) {
        CheckTotalModel record = null;
        try {
            QueryBuilder<CheckTotalModel, Integer> qb = dao.queryBuilder();
            qb.where().eq("year", year);
            qb.where().eq("month", month);
            qb.where().eq("day", day);
            qb = qb.limit(1l);
            PreparedQuery<CheckTotalModel> query = qb.prepare();
            List<CheckTotalModel> result = dao.query(query);
            if (result != null && result.size() > 0) {
                record = result.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return record;
    }

    public String findOneRecordSumMonth(int year, int month) {
        try {
            GenericRawResults results =dao.queryRaw("select sum(money) from check_total where year = ? and month = ?",year+"",month+"");
//            Iterator iterator = results.iterator();
//            List messageList = new ArrayList();
//            while (iterator.hasNext()) {
//
//            }
            String[] string = (String[]) results.getFirstResult();
            if(TextUtils.isEmpty(string[0])){
                return "0.0";
            }
            return string[0];
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "0.0";
    }
}
